package com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.dothantech.lpapi.IAtBitmap;
import com.dothantech.lpapi.LPAPI;
import com.dothantech.printer.IDzPrinter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jess.arms.base.BaseActivity;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.LogUtils;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoxing.zhinenghuacangku_zhijian.R;
import com.xiaoxing.zhinenghuacangku_zhijian.R2;
import com.xiaoxing.zhinenghuacangku_zhijian.di.component.DaggerQuYangCaoZuoComponent;
import com.xiaoxing.zhinenghuacangku_zhijian.di.module.QuYangCaoZuoModule;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.contract.QuYangCaoZuoContract;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.presenter.QuYangCaoZuoPresenter;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.adapter.QuYangCaoZuo1Adapter;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.entity.GetSimpleZoneBuffer;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.entity.QuYangCaoZuo;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.entity.QuYangLieBiao;
import com.xiaoxing.zhinenghuacangku_zhijian.mvp.ui.utils.PrinterUtil;

import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import com.jess.arms.utils.CProgressDialogUtils;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import me.jessyan.armscomponent.commonres.view.NiceSpinner;
import me.jessyan.armscomponent.commonres.view.RecycleViewDivider;
import me.jessyan.armscomponent.commonsdk.core.RouterHub;
import me.jessyan.armscomponent.commonsdk.utils.ButtonUtils;

import static com.jess.arms.utils.Preconditions.checkNotNull;


@Route(path = RouterHub.ZHI_NENG_HUA_CANG_KU_ZHI_JIAN_ACTIVITY_QU_YANG_CAO_ZUO)
public class QuYangCaoZuoActivity extends BaseActivity<QuYangCaoZuoPresenter> implements QuYangCaoZuoContract.View, QuYangCaoZuo1Adapter.IChouJianChuKuLieBiaoAdapter, OnRefreshListener, PrinterUtil.PrinterI {

    public LocationClient mLocationClient = null;
    @BindView(R2.id.empty_text)
    TextView empty_text;
    @BindView(R2.id.empty_image)
    ImageView empty_image;
    @BindView(R2.id.empty)
    View mEmptyLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.refreshLayout)
    RefreshLayout mRefreshLayout;
    PrinterUtil mPrinterUtil;
    private QuYangCaoZuo1Adapter mAdapter;
    private List<QuYangCaoZuo> mDataBeanList = new ArrayList<>();
    private List<QuYangLieBiao> groups = new ArrayList<QuYangLieBiao>();// 组元素数据列表
    private Map<String, List<QuYangLieBiao.MitemBean>> children = new HashMap<String, List<QuYangLieBiao.MitemBean>>();// 子元素数据列表
    private Map<Integer, Integer> mGroupsPosition = new HashMap<>();
    private AlertDialog mAlertDialog;
    private String mSelectedBufferId;
    private String mSelectedBufferName;
    private MyLocationListener myListener = new MyLocationListener();
    private Disposable disposable;

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerQuYangCaoZuoComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .quYangCaoZuoModule(new QuYangCaoZuoModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_qu_yang_cao_zuo; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {

        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.activity_qu_yang_cao_zuo));
        initRefreshLayout();
        initRecyclerView();
        initEmpty();
        initBaiDuLocation();
        initPrinter();

        getQuYangLieBiao();
        startTimer();
    }

    private void initRefreshLayout() {
        mRefreshLayout.setRefreshHeader(new
                ClassicsHeader(this).setSpinnerStyle(SpinnerStyle.FixedBehind).setPrimaryColorId(R.color.public_colorPrimary).setAccentColorId(android.R.color.white));
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setEnableLoadMore(false);
    }

    private void initRecyclerView() {

        mRecyclerView.setLayoutManager(new LinearLayoutManager(QuYangCaoZuoActivity.this));
        mRecyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 10, Color.parseColor("#EEEEEE")));

        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(mAdapter = new QuYangCaoZuo1Adapter(QuYangCaoZuoActivity.this, mDataBeanList, this));

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            }
        });

//        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, VERTICAL));
//        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
//        mRecyclerView.setAdapter(mAdapter = new QuYangCaoZuoAdapter(this, groups, children, mGroupsPosition));
//        //优化嵌套卡顿
//        mRecyclerView.setHasFixedSize(true);
//        mRecyclerView.setNestedScrollingEnabled(false);
//        mRecyclerView.setItemViewCacheSize(600);
//        RecyclerView.RecycledViewPool recycledViewPool = new RecyclerView.RecycledViewPool();
//        mRecyclerView.setRecycledViewPool(recycledViewPool);
//        mAdapter.setChuKuInterface(this);

    }

    private void initEmpty() {
        empty_image.setImageResource(R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void initBaiDuLocation() {
        //BDAbstractLocationListener为7.2版本新增的Abstract类型的监听接口
        //原有BDLocationListener接口暂时同步保留。具体介绍请参考后文第四步的说明
        mLocationClient = new LocationClient(getApplicationContext());
        //声明LocationClient类
        mLocationClient.registerLocationListener(myListener);
        //注册监听函数
        LocationClientOption option = new LocationClientOption();
        option.setIsNeedAddress(true);

        //可选，是否需要地址信息，默认为不需要，即参数为false
        //如果开发者需要获得当前点的地址信息，此处必须为true
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //可选，设置定位模式，默认高精度
        //LocationMode.Hight_Accuracy：高精度；
        //LocationMode. Battery_Saving：低功耗；
        //LocationMode. Device_Sensors：仅使用设备；

        option.setCoorType("bd09ll");
        //可选，设置返回经纬度坐标类型，默认GCJ02
        //GCJ02：国测局坐标；
        //BD09ll：百度经纬度坐标；
        //BD09：百度墨卡托坐标；
        //海外地区定位，无需设置坐标类型，统一返回WGS84类型坐标

        option.setScanSpan(10000);
//        option.setScanSpan(60000);
        //可选，设置发起定位请求的间隔，int类型，单位ms
        //如果设置为0，则代表单次定位，即仅定位一次，默认为0
        //如果设置非0，需设置1000ms以上才有效

        option.setOpenGps(true);
        //可选，设置是否使用gps，默认false
        //使用高精度和仅用设备两种定位模式的，参数必须设置为true


        option.setLocationNotify(true);
        //可选，设置是否当GPS有效时按照1S/1次频率输出GPS结果，默认false

        option.setIgnoreKillProcess(false);
        //可选，定位SDK内部是一个service，并放到了独立进程。
        //设置是否在stop的时候杀死这个进程，默认（建议）不杀死，即setIgnoreKillProcess(true)

        option.SetIgnoreCacheException(false);
        //可选，设置是否收集Crash信息，默认收集，即参数为false

        option.setWifiCacheTimeOut(5 * 60 * 1000);
        //可选，V7.2版本新增能力
        //如果设置了该接口，首次启动定位时，会先判断当前Wi-Fi是否超出有效期，若超出有效期，会先重新扫描Wi-Fi，然后定位

        option.setEnableSimulateGps(false);
        //可选，设置是否需要过滤GPS仿真结果，默认需要，即参数为false

        mLocationClient.setLocOption(option);
        //mLocationClient为第二步初始化过的LocationClient对象
        //需将配置好的LocationClientOption对象，通过setLocOption方法传递给LocationClient对象使用
        //更多LocationClientOption的配置，请参照类参考中LocationClientOption类的详细说明


        mLocationClient.start();
        //mLocationClient为第二步初始化过的LocationClient对象
        //调用LocationClient的start()方法，便可发起定位请求
    }

    private void initPrinter() {
        mPrinterUtil = new PrinterUtil(this);
        mPrinterUtil.setPrinterI(this);
        IDzPrinter.Factory.getInstance().init(this, mPrinterUtil.mCallback);
    }

    /**
     * @param
     * @return
     * @method
     * @description 获取质检列表
     * @date: 2020/9/3 0003 14:06
     * @author: 小星
     */
    private void getQuYangLieBiao() {
        showLoading();

        String methodNames = "SimpleOutedListForSimpling";
        SoapParams paramss = null;
        paramss = new SoapParams();
        paramss.put("uid", mSharedPreferencesHelper.getString(BaseConstants.UID));
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
//                        List<QuYangLieBiao> outOfTheLibraryLists = ArmsUtils.parseString2List(result, QuYangLieBiao.class);
//                        mGroupsPosition.clear();
//                        children.clear();
//                        groups.clear();
//                        mAdapter.setDataItems(getSampleItems(outOfTheLibraryLists));
//                        mAdapter.notifyDataSetChanged();
//                        mAdapter.expandAll();
//                        mEmptyLayout.setVisibility(View.GONE);
//                        mRecyclerView.setVisibility(View.VISIBLE);

                        List<QuYangCaoZuo> quYangCaoZuos = ArmsUtils.parseString2List(result, QuYangCaoZuo.class);

                        if (quYangCaoZuos != null && quYangCaoZuos.size() > 0) {
                            mDataBeanList.clear();
                            mDataBeanList.addAll(quYangCaoZuos);
                            mAdapter.notifyDataSetChanged();
                            mEmptyLayout.setVisibility(View.GONE);
                            mRecyclerView.setVisibility(View.VISIBLE);
                        } else {
                            mEmptyLayout.setVisibility(View.VISIBLE);
                            mRecyclerView.setVisibility(View.GONE);
                        }

                    } else {
                        mEmptyLayout.setVisibility(View.VISIBLE);
                        mRecyclerView.setVisibility(View.GONE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * 开始定时执行
     */
    private void startTimer() {
        stopTimer();
        disposable = Observable.interval(60, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Long aLong) throws Exception {
                        // 逻辑代码
                        getQuYangLieBiao();
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@io.reactivex.annotations.NonNull Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                    }
                });
    }

    @Override
    public void showLoading() {
        CProgressDialogUtils.showProgressDialog(this);
    }

    /**
     * 停止定时执行
     */
    protected void stopTimer() {
        if (null != disposable) {
            disposable.dispose();
            disposable = null;
        }
    }

    @Override
    public void hideLoading() {
        CProgressDialogUtils.cancelProgressDialog(this);
    }

//    public List<QuYangCaoZuoAdapter.OrderListItem> getSampleItems(List<QuYangLieBiao> quYangLieBiaos) {
//        List<QuYangCaoZuoAdapter.OrderListItem> items = new ArrayList<>();
//
//        for (int i = 0; i < quYangLieBiaos.size(); i++) {
//
//            int groupPosition = items.size();
//            mGroupsPosition.put(groupPosition, i);
//
//            QuYangLieBiao quYangLieBiao = quYangLieBiaos.get(i);
//
//            groups.add(quYangLieBiao);
//            items.add(new QuYangCaoZuoAdapter.OrderListItem(quYangLieBiao));
//
//            List<QuYangLieBiao.MitemBean> outList = quYangLieBiao.getMitem();
//
//            List<QuYangLieBiao.MitemBean> products = new ArrayList<QuYangLieBiao.MitemBean>();
//
//
//            for (int i1 = 0; i1 < outList.size(); i1++) {
//
//                QuYangLieBiao.MitemBean outListBean = outList.get(i1);
//
//
//                products.add(outListBean);
//
//                items.add(new QuYangCaoZuoAdapter.OrderListItem(groupPosition, outListBean, i1, quYangLieBiao));
//            }
//
//            children.put(String.valueOf(groupPosition), products);// 将组元素的一个唯一值，这里取Id，作为子元素List的Key
//
//        }
////        items.add(new OutOfTheLibraryAdapter.OrderListItem("", "", "", ""));
//
//        return items;
//    }
//
//    public void clearData() {
//        mGroupsPosition.clear();
//        children.clear();
//        groups.clear();
//        mEmptyLayout.setVisibility(View.VISIBLE);
//        mRecyclerView.setVisibility(View.GONE);
//    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mLocationClient != null) {
            mLocationClient.stop();
        }
        stopTimer();
    }

//    /**
//     * @param
//     * @return
//     * @method
//     * @description 点击出库按钮执行的方法：1、 先查询取样区 2、返回数据，弹出选择取样区的弹出框 3、选择取样区，点击取样
//     * @date: 2020/9/3 0003 16:47
//     * @author: 小星
//     */
//    @Override
//    public void chuKu(QuYangLieBiao quYangLieBiao) {
////        if (mPrinterUtil.selectPrinterCheck()) {
////        if (quYangLieBiao.getSendoutorder().equals("0")) {
//        getSimpleZoneBuffer(quYangLieBiao);
////        } else {
////            showMessage("已经发送过出库命令");
////        }
////        } else {
////            showMessage("请先连接二维码打印机");
////        }
//    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {

    }

    /**
     * @param
     * @return
     * @method
     * @description 查询取样区列表
     * @date: 2020/9/3 0003 16:22
     * @author: 小星
     */
    private void getSimpleZoneBuffer(QuYangLieBiao quYangLieBiao) {
        showLoading();

        String methodNames = "GetSimpleZoneBuffer";
        SoapParams paramss = null;
        paramss = new SoapParams();
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        showQuYangQu(result, quYangLieBiao);


                    } else {
//                        clearData();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * @param
     * @return
     * @method
     * @description 弹出取样区
     * @date: 2020/9/3 0003 16:46
     * @author: 小星
     */
    private void showQuYangQu(String result, QuYangLieBiao quYangLieBiao) {


        View myView = LayoutInflater.from(this).inflate(R.layout.zhi_neng_cang_ku_zhi_jian_layout_qu_yang_qu, null);
        NiceSpinner niceSpinner = myView.findViewById(R.id.nice_position);
        List<GetSimpleZoneBuffer> getSimpleZoneBuffers = new Gson().fromJson(result, new TypeToken<List<GetSimpleZoneBuffer>>() {
        }.getType());

        if (getSimpleZoneBuffers != null && getSimpleZoneBuffers.size() > 0) {
            initSpPosition(getSimpleZoneBuffers, niceSpinner);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("取样", null);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        mAlertDialog = builder.create();
        mAlertDialog.setTitle("选择取样区");
        mAlertDialog.setView(myView);
        mAlertDialog.show();


        //拿到按钮并判断是否是POSITIVEBUTTON，然后我们自己实现监听
        mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ButtonUtils.isFastDoubleClick()) {

                    List<QuYangLieBiao.MitemBean> mitemBeanList = quYangLieBiao.getMitem();
                    int random = new Random().nextInt(mitemBeanList.size());
                    QuYangLieBiao.MitemBean mitemBean = mitemBeanList.get(random);
//                    if (mitemBean.getIsauto().equals("1")) {
//                        simpleOutStoreForQuality(quYangLieBiao, mitemBean);
//                    } else if (mitemBean.getIsauto().equals("0")) {
//                        peopleSendToSimpleOrder(quYangLieBiao, mitemBean);
//                    }
                    sendSimpleOrderToCGY(quYangLieBiao, mitemBean);
                    mAlertDialog.dismiss();
                } else {
                    showMessage("10s内请勿重复点击");
                }

            }
        });


    }

    private void initSpPosition(List<GetSimpleZoneBuffer> getSimpleZoneBuffers, NiceSpinner spPosition) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < getSimpleZoneBuffers.size(); i++) {
            list.add(String.valueOf(
                    new StringBuilder()
                            .append(getSimpleZoneBuffers.get(i).getBuffer_name())
            ));
        }
        mSelectedBufferId = getSimpleZoneBuffers.get(0).getId();
        mSelectedBufferName = getSimpleZoneBuffers.get(0).getBuffer_name();
        spPosition.attachDataSource(list);
        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelectedBufferId = getSimpleZoneBuffers.get(position).getId();
                mSelectedBufferName = getSimpleZoneBuffers.get(position).getBuffer_name();
            }
        });
    }

//    @Override
//    public void queDing(QuYangLieBiao quYangLieBiao) {
//        if (mPrinterUtil.selectPrinterCheck()) {
//            createSimpleCodeSaveGPS(quYangLieBiao);
//        } else {
//            showMessage("请先连接二维码打印机");
//        }
//    }

    /**
     * @param
     * @return
     * @method
     * @description 显示"取样"按钮,点击调用
     * @date: 2020/9/4 0004 10:51
     * @author: 小星
     */
    private void sendSimpleOrderToCGY(QuYangLieBiao quYangLieBiao, QuYangLieBiao.MitemBean mitemBean) {

        showLoading();
        String methodNames = "SendSimpleOrderToCGY";
        SoapParams paramss = null;
        paramss = new SoapParams();
        paramss.put("mid", mitemBean.getMid());
        paramss.put("spname", mitemBean.getSpname());
        paramss.put("spid", mitemBean.getSpid());
        paramss.put("bufferid", mSelectedBufferId);
        paramss.put("buffer_name", mSelectedBufferName);
        paramss.put("monthid", quYangLieBiao.getMonthid());
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100") && !result.equals("true")) {
                        showMessage("取样命令发送成功");
                        //命令发送成功，重新查询取样列表
                        getQuYangLieBiao();
                    } else {
                        showMessage("取样命令发送失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void onProgressInfo(String info) {

    }

    @Override
    public void onStateChange(String info) {

    }

    @Override
    public void onPrintProgress(String info) {

    }

    @Override
    public void onPrinterDiscovery(String info) {

    }

    @Override
    public void connectSuccess(String info) {

    }

    @Override
    public void Connecting(String info) {

    }

    @Override
    public void connectFail(String info) {

    }

    @Override
    public void printSuccess() {

    }

    @Override
    public void printFail() {

    }

    @Override
    public void getQuYangCaoZuoDataSuccess(QuYangCaoZuo entityData) {


    }

    @Override
    public void shengChengQuYangMa(QuYangCaoZuo quYangCaoZuo) {
        if (mPrinterUtil.selectPrinterCheck()) {

            createSimpleCodeSaveGPS(quYangCaoZuo);
        } else {
            showMessage("请先连接二维码打印机");
        }
    }

    //
//    @Override
//    public void daYinQuYangMa(QuYangLieBiao quYangLieBiao) {
//        //打印取样码
//        if (mPrinterUtil.selectPrinterCheck()) {
//            printBigQRcodeOriention(quYangLieBiao.getMonthid());
//        } else {
//            showMessage("请先连接二维码打印机");
//        }
//
//    }
//
    @Override
    public void renGongYunZhiFengQianQu(String type, QuYangCaoZuo quYangCaoZuo) {
        getSimpleMaskZoneBuffer(type, quYangCaoZuo);
    }

    /**
     * @param
     * @return
     * @method
     * @description 获取封签区列表，显示按钮"人工运至封签区" 点击后  弹出窗体 调用
     * public string GetSimpleMaskZoneBuffer() 获取封签区
     * @date: 2020/9/3 0003 21:07
     * @author: 小星
     */
    private void getSimpleMaskZoneBuffer(String type, QuYangCaoZuo quYangCaoZuo) {
        showLoading();

        String methodNames = "GetSimpleMaskZoneBuffer";
        SoapParams paramss = null;
        paramss = new SoapParams();
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {

                        if (type.equals("0")) {//type 为0 人工运至封签区
                            showRenGongToFengQianQu(result, quYangCaoZuo);
                        } else if (type.equals("1")) {//type 为1 AGV运至封签区
                            showAGVToFengQianQu(result, quYangCaoZuo);

                        }
                    } else {

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * @param
     * @return
     * @method
     * @description 封签区人工择弹出框
     * @date: 2020/9/3 0003 21:11
     * @author: 小星
     */
    private void showRenGongToFengQianQu(String result, QuYangCaoZuo quYangCaoZuo) {


        View myView = LayoutInflater.from(this).inflate(R.layout.zhi_neng_cang_ku_zhi_jian_layout_qu_yang_qu, null);
        NiceSpinner niceSpinner = myView.findViewById(R.id.nice_position);
        List<GetSimpleZoneBuffer> getSimpleZoneBuffers = new Gson().fromJson(result, new TypeToken<List<GetSimpleZoneBuffer>>() {
        }.getType());

        if (getSimpleZoneBuffers != null && getSimpleZoneBuffers.size() > 0) {
            initFengQianQuPosition(getSimpleZoneBuffers, niceSpinner);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("人工发运", null);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        mAlertDialog = builder.create();
        mAlertDialog.setTitle("选择封签区");
        mAlertDialog.setView(myView);
        mAlertDialog.show();


        //拿到按钮并判断是否是POSITIVEBUTTON，然后我们自己实现监听
        mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ButtonUtils.isFastDoubleClick()) {

                    peopleSendFromSimpleToMaskOrder(quYangCaoZuo);
                    mAlertDialog.dismiss();
                } else {
                    showMessage("10s内请勿重复点击");
                }

            }
        });


    }

    /**
     * @param
     * @return
     * @method
     * @description 封签区AGV选择弹出框
     * @date: 2020/9/3 0003 21:11
     * @author: 小星
     */
    private void showAGVToFengQianQu(String result, QuYangCaoZuo quYangCaoZuo) {


        View myView = LayoutInflater.from(this).inflate(R.layout.zhi_neng_cang_ku_zhi_jian_layout_qu_yang_qu, null);
        NiceSpinner niceSpinner = myView.findViewById(R.id.nice_position);
        List<GetSimpleZoneBuffer> getSimpleZoneBuffers = new Gson().fromJson(result, new TypeToken<List<GetSimpleZoneBuffer>>() {
        }.getType());

        if (getSimpleZoneBuffers != null && getSimpleZoneBuffers.size() > 0) {
            initFengQianQuPosition(getSimpleZoneBuffers, niceSpinner);
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setPositiveButton("发送命令", null);
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        mAlertDialog = builder.create();
        mAlertDialog.setTitle("选择封签区");
        mAlertDialog.setView(myView);
        mAlertDialog.show();


        //拿到按钮并判断是否是POSITIVEBUTTON，然后我们自己实现监听
        mAlertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!ButtonUtils.isFastDoubleClick()) {

                    sendAGVFromSimpleToMaskOrder(quYangCaoZuo);
                    mAlertDialog.dismiss();
                } else {
                    showMessage("10s内请勿重复点击");
                }

            }
        });


    }

    private void initFengQianQuPosition(List<GetSimpleZoneBuffer> getSimpleZoneBuffers, NiceSpinner spPosition) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i < getSimpleZoneBuffers.size(); i++) {
            list.add(String.valueOf(
                    new StringBuilder()
                            .append(getSimpleZoneBuffers.get(i).getBuffer_name())
            ));
        }
        mSelectedBufferId = getSimpleZoneBuffers.get(0).getId();
        mSelectedBufferName = getSimpleZoneBuffers.get(0).getBuffer_name();
        spPosition.attachDataSource(list);
        spPosition.addOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mSelectedBufferId = getSimpleZoneBuffers.get(position).getId();
                mSelectedBufferName = getSimpleZoneBuffers.get(position).getBuffer_name();
            }
        });
    }

    /**
     * @param
     * @return
     * @method
     * @description "人工发运" 调用
     * @date: 2020/9/3 0003 21:10
     * @author: 小星
     */
    private void peopleSendFromSimpleToMaskOrder(QuYangCaoZuo quYangCaoZuo) {
        showLoading();

        String methodNames = "PeopleSendFromSimpleToMaskOrder";
        SoapParams paramss = null;
        paramss = new SoapParams();
        paramss.put("mid", quYangCaoZuo.getMid());
        paramss.put("monthid", quYangCaoZuo.getMonthid());
        paramss.put("to_buffer", mSelectedBufferName);

        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100") && !result.equals("false")) {
                        showMessage("人工发运成功");
                        getQuYangLieBiao();
                    } else {
                        showMessage("人工发运失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    /**
     * @param
     * @return
     * @method
     * @description AGV运至封签区--发送命令
     * @date: 2020/9/3 0003 21:23
     * @author: 小星
     */
    private void sendAGVFromSimpleToMaskOrder(QuYangCaoZuo quYangCaoZuo) {
        showLoading();

        String methodNames = "SendAGVFromSimpleToMaskOrder";
        SoapParams paramss = null;
        paramss = new SoapParams();
        paramss.put("mid", quYangCaoZuo.getMid());
        paramss.put("monthid", quYangCaoZuo.getMonthid());
        paramss.put("to_buffer", mSelectedBufferName);

        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100") && !result.equals("false")) {
                        showMessage("发送命令成功");
                    } else {
                        showMessage("发送命令失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    @Override
    public void agvYunZhiFengQianQu(String type, QuYangCaoZuo quYangCaoZuo) {
        getSimpleMaskZoneBuffer(type, quYangCaoZuo);

    }

    /**
     * @param
     * @return
     * @method
     * @description 货物到位后 点击确认 调用   sendoutorder=1 则 显示一句话 旁边加个"确认"按钮
     * 确认将{spotnum}{spotunit}{material}从{spname}放至{buffername}
     * {spotnum}{spotunit}{material}{spname}是SimpleOutStoreListForQuality返回的
     * buffername是GetSimpleZoneBuffer返回的buffername
     * @date: 2020/9/3 0003 20:28
     * @author: 小星
     */
    private void createSimpleCodeSaveGPS(QuYangCaoZuo quYangCaoZuo) {
        showLoading();

        String methodNames = "createSimpleCodeSaveGPS";
        SoapParams paramss = null;
        paramss = new SoapParams();
        paramss.put("monthid", quYangCaoZuo.getMonthid());
        paramss.put("lng", mSharedPreferencesHelper.getString(BaseConstants.LNG));
        paramss.put("lat", mSharedPreferencesHelper.getString(BaseConstants.LAT));
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodNames, paramss, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                hideLoading();
                try {
                    String result = object.getProperty(methodNames + "Result").toString();
                    if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                        showMessage("生成取样码成功");
                        //打印取样码
                        printBigQRcodeOriention(result);
                        getQuYangLieBiao();
                    } else {
                        showMessage("生成取样码失败");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                hideLoading();
            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                hideLoading();

            }
        }, getAapiUserName(), getApiPwd());
    }

    public static void printBigQRcodeOriention(String content) {

        // 得到 IDzPrinter 对象
        IDzPrinter printer = IDzPrinter.Factory.getInstance();
        // 连接配对的第一个打印机对象
        printer.connect(IDzPrinter.Factory.getFirstPrinter());
        // 创建 IAtBitmap 绘图对象
        IAtBitmap api = IAtBitmap.Factory.createInstance();
        // 开始绘图任务，传入参数(页面宽度, 页面高度)
        api.setItemHorizontalAlignment(LPAPI.ItemAlignment.LEFT);
        api.setItemOrientation(180);

        api.startJob(50 * 100, 50 * 100);//48, 50
//        api.setItemOrientation(180);
        api.drawText("取样码", 27 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//        api.drawText("取样码:" + content, 30 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
        api.draw2DQRCode(content, 14 * 100, 13 * 100, 20 * 100);//  9, 10, 20,30
//        // 开始一个页面的绘制，绘制二维码
//        if (name.length() > 19) {
//            if (name.substring(19).length() > 23) {
//                api.drawText("入库时间:" + time, 46 * 100, 4 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("" + name.substring(42), 46 * 100, 7 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("" + name.substring(19, 42), 46 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("物料名称:" + name.substring(0, 19), 46 * 100, 13 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("项目编号:" + proid, 46 * 100, 16 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("核对序号:" + content, 46 * 100, 19 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
////                api.drawText("数量:" + num, 16 * 100, 12 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
//                api.drawText("订单号:" + orderNo, 46 * 100, 22 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.draw2DQRCode(content, 14 * 100, 23 * 100, 17 * 100);//  9, 10, 20,30
//            } else {
//                api.drawText("入库时间:" + time, 46 * 100, 4 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("" + name.substring(19), 46 * 100, 7 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("物料名称:" + name.substring(0, 19), 46 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("项目编号:" + proid, 46 * 100, 13 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.drawText("核对序号:" + content, 46 * 100, 16 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
////                api.drawText("数量:" + num, 16 * 100, 9 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
//                api.drawText("订单号:" + orderNo, 46 * 100, 19 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//                api.draw2DQRCode(content, 14 * 100, 20 * 100, 20 * 100);//  9, 10, 20,30
//            }
//
//        } else {
//            api.drawText("入库时间:" + time, 46 * 100, 4 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("物料名称:" + name, 46 * 100, 7 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("项目编号:" + proid, 46 * 100, 10 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.drawText("核对序号:" + content, 46 * 100, 13 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
////            api.drawText("数量:" + num, 16 * 100, 6 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR);
//            api.drawText("订单号:" + orderNo, 46 * 100, 16 * 100, 0, 0, 2 * 100, IAtBitmap.FontStyle.REGULAR, 0);
//            api.draw2DQRCode(content, 14 * 100, 17 * 100, 20 * 100);//  9, 10, 20,30
//        }

        // 结束绘图任务
        api.endJob();
        // 打印
        printer.print(api, null);

    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            //此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            //以下只列举部分获取经纬度相关（常用）的结果信息
            //更多结果信息获取说明，请参照类参考中BDLocation类中的说明
            if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
                double latitude = location.getLatitude();    //获取纬度信息
                double longitude = location.getLongitude();    //获取经度信息
                float radius = location.getRadius();    //获取定位精度，默认值为0.0f

                String coorType = location.getCoorType();
                //获取经纬度坐标类型，以LocationClientOption中设置过的坐标类型为准

                int errorCode = location.getLocType();
                //获取定位类型、定位错误返回码，具体信息可参照类参考中BDLocation类中的说明
                mSharedPreferencesHelper.putString(BaseConstants.LAT, String.valueOf(latitude));
                mSharedPreferencesHelper.putString(BaseConstants.LNG, String.valueOf(longitude));
                EventBus.getDefault().post(location, "setAddress");
//                tvl.setText(location.getAddrStr());
                LogUtils.debugEInfo("onReceiveLocation==" + location.getAddrStr());
            }//此处的BDLocation为定位结果信息类，通过它的各种get方法可获取定位相关的全部结果
            else if (location.getLocType() == BDLocation.TypeOffLineLocation) {
                // 离线定位成功
                Log.i("baidu_location_result", "offline location success");
                double lat = location.getLatitude();
                double lon = location.getLongitude();
//                tv_location.setText("lat=" + lat + " lon=" + lon);
//                showMessage("lat=" + lat + " lon" + lon);
//                EventBus.getDefault().post();
                mSharedPreferencesHelper.putString(BaseConstants.LAT, String.valueOf(lat));
                mSharedPreferencesHelper.putString(BaseConstants.LNG, String.valueOf(lon));
                EventBus.getDefault().post(location, "setAddress");

            } else if (location.getLocType() == BDLocation.TypeGpsLocation) {
                // GPS定位成功
                Log.i("baidu_location_result", "Gps location success");
                double lat = location.getLatitude();
                double lon = location.getLongitude();
//                tv_location.setText("lat=" + lat + " lon=" + lon);
//                showMessage("lat=" + lat + " lon" + lon);
                mSharedPreferencesHelper.putString(BaseConstants.LAT, String.valueOf(lat));
                mSharedPreferencesHelper.putString(BaseConstants.LNG, String.valueOf(lon));
                EventBus.getDefault().post(location, "setAddress");


            } else if (location.getLocType() == BDLocation.TypeOffLineLocationFail) {
                // 离线定位失败
                Log.i("baidu_location_result", "offline location fail");
                showMessage("GPS信号弱,定位失败,请到空旷的位置重新定位。");
            } else if (location.getLocType() == BDLocation.TypeOffLineLocationNetworkFail) {
                // 离线定位失败
                Log.i("baidu_location_result", "Network location fail");
                showMessage("网络信号弱,定位失败,请检查网络状态。");
            } else {

                Log.i("baidu_location_result", "location type = " + location.getLocType());
//                showMessage("location type = " + location.getLocType());

            }

        }
    }
}
